﻿using ICSharpCode.SharpZipLib.Zip;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace InstitutionAssitant
{
    public partial class frmUpdate : Form
    {
        public string _VersionName = "";
        public int _newVersion = 0;
        public string _hasValue = "";
        public frmUpdate()
        {
            InitializeComponent();
        }

        private async void frmUpdate_Load(object sender, EventArgs e)
        {
            string url = DbHelper._getAutoUpdateAddress() + "/Api/Scheme/DownloadVersionPackage?hasValue=" + _hasValue;

            string downloadurl = HisInterFace.GetUrl(url);
            downloadurl = downloadurl.Replace("\"", "");
            string _files = AppDomain.CurrentDomain.BaseDirectory + "\\DBlog\\download" + DateTime.Now.ToString("MMddHHmmssfff") + ".txt";
            FileSystemObject.Create(_files, FsoMethod.File);
            FileSystemObject.WriteFile(_files, "url:" + url + "\r\n");
            FileSystemObject.WriteFile(_files, "downloadurl:" + downloadurl + "\r\n", true);

            string filename = _getDownloadFile(downloadurl);
            if (!filename.Equals(""))
            {
                //关闭当前运行的程序
                string currentExecutable = Process.GetCurrentProcess().MainModule.FileName;
                
                //Process[] proc = System.Diagnostics.Process.GetProcessesByName("InstitutionAssitant");
                //关闭原有应用程序的所有进程
                //foreach (System.Diagnostics.Process pro in proc)
                //{
                //    pro.Start();
                //    pro.WaitForExit();
                //}
                string files = AppDomain.CurrentDomain.BaseDirectory + filename;
                progressBar1.Value = 0;
                lblInfo.Text = "下载中...";
                await DownloadFileAsync(downloadurl, files);
                progressBar1.Value = 0;
                lblInfo.Text = "解压中...";
                //解压更新包
                await Task.Run(() => UnzipFile(files, AppDomain.CurrentDomain.BaseDirectory));
                lblInfo.Text = "解压完成，重启程序！";
                //更新配置文件当前最新版本号
                DbHelper._setCurrentVersion(_newVersion.ToString());
                DbHelper._setCurrentVersionName(_VersionName);
                //重启程序
                
                Environment.Exit(0);
                Application.ExitThread();
                Application.Exit();
            }
        }

        private string _getDownloadFile(string downurl)
        {
            string[] _filearr = downurl.Split('/');
            if (_filearr.Length > 0)
                return _filearr[_filearr.Length - 1];
            else
                return "";
        }
        /// <summary>
        /// 异步调用下载更新文件
        /// </summary>
        /// <param name="url"></param>
        /// <param name="destinationPath"></param>
        /// <returns></returns>
        private async Task DownloadFileAsync(string url, string destinationPath)
        {
            using (HttpClient client = new HttpClient())
            {
                using (HttpResponseMessage response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead))
                {
                    _ = response.EnsureSuccessStatusCode();

                    long? totalBytes = response.Content.Headers.ContentLength;

                    using (var stream = await response.Content.ReadAsStreamAsync())
                    using (var fileStream = new FileStream(destinationPath, FileMode.Create, FileAccess.Write, FileShare.None, 8192, true))
                    {
                        var buffer = new byte[8192];
                        long totalRead = 0;
                        int bytesRead;

                        while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length)) != 0)
                        {
                            await fileStream.WriteAsync(buffer, 0, bytesRead);
                            totalRead += bytesRead;

                            if (totalBytes.HasValue)
                            {
                                int progress = (int)((double)totalRead / totalBytes.Value * 100);
                                _ = Invoke(new Action(() => progressBar1.Value = progress));
                            }
                        }
                    }
                }
            }
        }
        

        public void UnzipFile(string zipFilePath, string destinationFolder)
        {
            // 确保目标文件夹存在
            Directory.CreateDirectory(destinationFolder);

            // 打开ZIP文件
            using (var zipToOpen = new FileStream(zipFilePath, FileMode.Open))
            {
                using (var archive = new ZipArchive(zipToOpen, ZipArchiveMode.Read))
                {
                    int totalEntries = archive.Entries.Count;
                    int extractedEntries = 0;
                    foreach (var entry in archive.Entries)
                    {
                        // 解压每个ZIP条目
                        if (entry.Length == 0) continue; // 忽略空条目

                        // 定义目标文件路径
                        var destFileName = Path.Combine(destinationFolder, entry.FullName);

                        // 确保文件夹路径存在
                        var destinationDirectory = Path.GetDirectoryName(destFileName);
                        Directory.CreateDirectory(destinationDirectory);

                        // 将文件内容复制到目标路径
                        using (var entryStream = entry.Open())
                        using (var fileStream = new FileStream(destFileName, FileMode.Create))
                        {
                            entryStream.CopyTo(fileStream);
                            extractedEntries++;
                            int progress = (int)((double)extractedEntries / totalEntries * 100);
                            _ = Invoke(new Action(() => progressBar1.Value = progress));
                        }                        
                    }
                }
            }
        }
    }
}
